package com.xgame.util.goods;

import java.util.ArrayList;

import java.util.List;

import java.util.Random;


/**
 * 
 * @author zhaowei
 * 
 * @date 2012-10-3
 * 
 * @desc:
 * 
 *        抽奖主类
 */

public class RunnerLottery {

	public static List<RunnerReward> randomList;

	/**
	 * 
	 * 获取中奖编码数组
	 * 
	 * @param rlist
	 * 
	 * @param keyLength
	 * 
	 * @return
	 */

	public List<RunnerReward> getKeys(List<RunnerReward> rlist, int keyLength) {

		List<RunnerReward> list = new ArrayList<RunnerReward>();

		for (int i = 0; i < keyLength; i++) {

			list.add(getKey(rlist));

		}

		return list;

	}

	/**
	 * 
	 * 获取中奖编码
	 * 
	 * @param rlist
	 * 
	 * @return
	 */

	private RunnerReward getKey(List<RunnerReward> rlist) {

		// 随机列表

		List<RunnerReward> randomList = getRandomList(rlist);

		// 根据随机列表得到的概率区段

		List<Integer> percentSteps = getPercentSteps(rlist);

		// 概率区段的最大值

		int maxPercentStep = percentSteps.get(percentSteps.size() - 1);

		// 在概率区段范围内取一个随机数

		int randomStep = new Random().nextInt(maxPercentStep);

		// 中间元素的下标

		int keyIndex = 0;

		int begin = 0;

		int end = 0;

		for (int i = 0; i < percentSteps.size(); i++) {

			if (i == 0) {

				begin = 0;

			} else {

				begin = percentSteps.get(i - 1);

			}

			end = percentSteps.get(i);

			// 判断随机数值是否在当前区段范围内

			if (randomStep > begin && randomStep <= end) {

				keyIndex = i;

				break;

			}

		}

		return randomList.get(keyIndex);

	}

	/**
	 * 
	 * 获取概率区段[如：10,15,25,30,40,60,75,80,90,95,100]
	 * 
	 * @param rlist
	 * 
	 * @return
	 */

	private List<Integer> getPercentSteps(List<RunnerReward> rlist) {

		List<Integer> percentSteps = new ArrayList<Integer>();

		int percent = 0;

		for (RunnerReward r : rlist) {

			percent += r.succPercent;

			percentSteps.add(percent);

		}

		return percentSteps;

	}

	/**
	 * 
	 * 获取随机列表
	 * 
	 * @param rlist
	 * 
	 * @return
	 */

	private List<RunnerReward> getRandomList(List<RunnerReward> rlist) {

		List<RunnerReward> oldList = new ArrayList<RunnerReward>(rlist);

		List<RunnerReward> newList = new ArrayList<RunnerReward>();

		// 随机排序的老序列中元素的下标

		int randomIndex = 0;

		// 随机排序下标的取值范围

		int randomLength = 0;

		for (int i = 0; i < rlist.size(); i++) {

			// 指向下标范围

			randomLength = oldList.size() - 1;

			// 取值范围元素的个数为多个时，从中随机选取一个元素的下标

			if (randomLength != 0) {

				randomIndex = new Random().nextInt(randomLength);

				// 取值范围元素的个数为一个时，直接返回该元素的下标

			} else {

				randomIndex = 0;

			}

			// 在新的序列当中添加元素，同时删除元素取值范围中的randomIndex下标所对应的元素

			newList.add(oldList.remove(randomIndex));

		}

		return newList;

	}

}